import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

export async function PATCH(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const goodsId = searchParams.get("goodsId");
    const body = await request.json();

    if (!goodsId) {
      return NextResponse.json({ error: "商品 ID 不能为空" }, { status: 400 });
    }

    // 更新商品的所有可编辑字段
    const updatedCommodity = await prisma.commodity.update({
      where: { goodsId: Number(goodsId) },
      data: {
        goodsName: body.goodsName,
        goodsPrice: body.goodsPrice,
        gDesc: body.gDesc,
        goodsAddress: body.goodsAddress,
        categoryId: body.categoryId || null,
        ImgUrl: body.ImgUrl,
        dvForm: body.dvForm || "送货到寝",
        prcForm: body.prcForm || "一口价",
        state: body.state || 1,
      },
    });

    return NextResponse.json({ commodity: updatedCommodity }, { status: 200 });
  } catch (error) {
    console.error("更新商品失败:", error);
    return NextResponse.json({ error: "更新商品失败" }, { status: 500 });
  }
}

export async function GET() {
  try {
    // 从数据库获取所有商品，并关联用户和分类信息
    const commodities = await prisma.commodity.findMany({
      select: {
        goodsId: true,
        openId: true,
        goodsName: true,
        ImgUrl: true,
        gDesc: true,
        goodsPrice: true,
        goodsAddress: true,
        dvForm: true,
        prcForm: true,
        categoryId: true,
        pbTime: true,
        state: true,
        user: {
          select: {
            uName: true,
          },
        },
        category: {
          select: {
            categoryName: true,
          },
        },
      },
    });

    // 格式化数据以匹配前端期望的结构
    const formattedCommodities = commodities.map((commodity) => ({
      goodsId: commodity.goodsId,
      openId: commodity.openId,
      goodsName: commodity.goodsName,
      ImgUrl: commodity.ImgUrl,
      gDesc: commodity.gDesc,
      goodsPrice: commodity.goodsPrice,
      goodsAddress: commodity.goodsAddress,
      dvForm: commodity.dvForm,
      prcForm: commodity.prcForm,
      categoryId: commodity.categoryId,
      pbTime: commodity.pbTime,
      state: commodity.state,
      userName: commodity.user.uName,
      categoryName: commodity.category?.categoryName || null,
    }));

    return NextResponse.json(
      { commodities: formattedCommodities },
      { status: 200 }
    );
  } catch (error) {
    console.error("获取商品数据失败:", error);
    return NextResponse.json({ error: "获取商品数据失败" }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const {
      goodsName,
      goodsPrice,
      gDesc,
      goodsAddress,
      categoryId,
      ImgUrl,
      dvForm,
      prcForm,
      openId,
      state,
    } = body;

    // 验证必要字段
    if (!goodsName || goodsPrice <= 0 || !goodsAddress) {
      return NextResponse.json(
        { error: "商品名称、价格和地址不能为空" },
        { status: 400 }
      );
    }

    // 创建商品记录
    const commodity = await prisma.commodity.create({
      data: {
        goodsName,
        goodsPrice,
        gDesc,
        goodsAddress,
        categoryId: categoryId || null,
        ImgUrl:
          ImgUrl ||
          "https://img1.baidu.com/it/u=415449740,540746270&fm=253&fmt=auto&app=138&f=GIF?w=500&h=500",
        dvForm: dvForm || "送货到寝",
        prcForm: prcForm || "一口价",
        openId: openId || "admin",
        state: state || 1,
        pbTime: new Date(),
      },
    });

    return NextResponse.json(
      {
        message: "商品创建成功",
        commodity,
      },
      { status: 201 }
    );
  } catch (error) {
    console.error("创建商品失败:", error);
    return NextResponse.json({ error: "创建商品失败" }, { status: 500 });
  }
}

export async function DELETE(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const goodsId = searchParams.get("goodsId");

    if (!goodsId) {
      return NextResponse.json({ error: "商品 ID 不能为空" }, { status: 400 });
    }

    // 删除指定商品
    await prisma.commodity.delete({
      where: { goodsId: Number(goodsId) },
    });

    return NextResponse.json({ message: "商品删除成功" }, { status: 200 });
  } catch (error) {
    console.error("删除商品失败:", error);
    return NextResponse.json({ error: "删除商品失败" }, { status: 500 });
  }
}
